<?php

namespace App\Repository\AppUser;

use App\Models\AppUser\TouTiaoUserOrderModel as model;
use App\Repository\BaseRepository;
use Illuminate\Support\Facades\DB;
use App\Repository\UploadRepository;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;

class TouTiaoPayOrderRepository extends  BaseRepository
{
  public function __construct()
  {
    $this->log = new Logger('TouTiaoPay');
    $this->log->pushHandler(
      (new RotatingFileHandler(storage_path('/logs/TouTiaoPay.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
    );
    // parent::__construct();
  }
  // 抖音支付
  // 抖音预下单 接口
  public function preOrder($array = array())
  {
    // 抖音预下单 
    $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_order';
    $data = [
      'app_id' => $array['app_id'],
      'out_order_no' => $array['out_order_no'],
      'total_amount' => $array['total_amount'],
      'subject' => $array['subject'],
      'body' => !empty($array['body']) ? $array['body'] : $array['subject'],
      'valid_time' => 900,
      'notify_url' => 'https://adminnew.chenqiwangluo.com/api/v1/douyinPAy',
    ];
    $data['sign'] = $this->getSign($data);
    $header = [
      'Content-Type:application/json'
    ];
    $res = $this->sendDouYin($url, $data, $header);
    $this->log->info('参数:' . json_encode($data) . '提交url:' . $url . '返回结果:' . json_encode($res));
    return json_decode($res, true);
  }
  // 抖音退款
  public function refundOrder($array = array())
  {
    $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/create_refund';
    $data  = [
      'app_id' => $array['app_id'],
      'out_order_no' => $array['ordersno'],
      'out_refund_no' => $array['out_refund_no'],
      'reason' => $array['reason'],
      'refund_amount' => $array['money'],
      'notify_url' => 'https://adminnew.chenqiwangluo.com/api/v1/douyinPAy'
    ];
    $data['sign'] = $this->getSign($data);
    $header = [
      'Content-Type:application/json'
    ];
    $res = $this->sendDouYin($url, $data, $header);
    $this->log->info('退款参数:' . json_encode($data) . '提交url:' . $url . '返回结果:' . json_encode($res));
    return json_decode($res, true);
  }
  /**
   * 查询订单接口
   *
   * @param Request $request
   * @return void
   */
  public function getQueryOrder($data = array())
  {
    $url = 'https://developer.toutiao.com/api/apps/ecpay/v1/query_order';
    $data = [
      'app_id' => '',
      'out_order_no' => '',
      'sign' => ''
    ];
    $header = [
      'Content-Type:application/json'
    ];
    $res = $this->sendDouYin($url, $data, $header);
    return $res;
  }
  /**
   * 推送订单 推送给抖音店铺的订单
   *
   * @return void
   */
  public function pushOrder($array = array())
  {
    /**
     * 0：待支付
        1：已支付
        2：已取消
        4：已核销（核销状态是整单核销,即一笔订单买了 3 个券，核销是指 3 个券核销的整单）
        5：退款中
        6：已退款
        8：退款失败
     */
    if (!empty($array['access_token_json'])) {
      // 这个地方是 数据表中查出来的字符串
      $resGetAccess = json_decode($array['access_token_json'], true);
      // var_dump($resGetAccess);
    }
    if (empty($array['access_token_json'])) {
      // 这个地方是数组
      $resGetAccess = $this->getAccessToken($array);
    }
    if (empty($resGetAccess) || empty($resGetAccess['access_token']) || empty($resGetAccess['time'])) {
      return $this->returnMsg(103, '请联系商家,未获取到权限');
    }
    if ($resGetAccess['time'] < time()) {
      // var_dump($resGetAccess, 99999999);
      $resGetAccess = $this->getAccessToken($array);
    }
    if (empty($resGetAccess['access_token']) || empty($resGetAccess['time'])) {
      return $this->returnMsg(104, 'access_token未获取到');
    }
    // var_dump($resGetAccess);
    $url = 'https://developer.toutiao.com/api/apps/order/v2/push';
    $sstatus = '';
    switch ($array['status']) {
      case 1:
        $sstatus = '待支付';
        break;
      case 2:
        $sstatus = '已支付';
        break;
      case 3:
        $sstatus = '退款中';
        break;
      case 6:
        $sstatus = '已退款';
        break;
    }
    $data = [
      'access_token' => $resGetAccess['access_token'],
      'app_name' => 'douyin',
      'open_id' => (string)$array['open_id'],
      'order_detail' => json_encode([
        'order_id' => (string)$array['out_order_no'],
        'create_time' => (int)(time() . get_millisecond()),
        'status' => $sstatus,
        'amount' => (int)($array['total_amount']),
        'total_price' => (int)$array['total_amount'],
        'detail_url' => (string)$array['path'],
        'item_list' => [[
          'item_code' => (string)$array['goods_id'],
          'img' => (string)$array['img'],
          'title' => (string)$array['subject'],
          // 'sub_title' => (string)$array['body'],
          // 'amount' => 1,
          'price' => (int)$array['total_amount']
        ]],
      ], JSON_UNESCAPED_UNICODE),
      'order_status' => 1,
      'order_type' => 0,
      'update_time' => (int)(time() . get_millisecond()),
    ];
    $header = [
      'Content-Type:application/json'
    ];
    $res = $this->sendDouYin($url, $data, $header);
    $this->log->info('参数:' . json_encode($data) . '提交url:' . $url . '返回结果:' . json_encode($res, JSON_UNESCAPED_UNICODE));
    return json_decode($res, true);
  }
  public function getKefuUrl($array = array())
  {
    if (!empty($array['access_token_json'])) {
      // 这个地方是 数据表中查出来的字符串
      $resGetAccess = json_decode($array['access_token_json'], true);
    }
    if (empty($array['access_token_json'])) {
      // 这个地方是数组
      $resGetAccess = $this->getAccessToken($array);
    }
    if (empty($resGetAccess) || empty($resGetAccess['access_token']) || empty($resGetAccess['time'])) {
      return $this->returnMsg(103, '请联系商家,未获取到权限');
    }
    if ($resGetAccess['time'] < time()) {
      $resGetAccess = $this->getAccessToken($array);
    }
    if (empty($resGetAccess['access_token']) || empty($resGetAccess['time'])) {
      return $this->returnMsg(104, 'access_token未获取到');
    }
    $url = 'https://developer.toutiao.com/api/apps/chat/customer_service_url';
    $data = [
      'appid' => $array['app_id'],
      'openid' => $array['open_id'],
      'type' => 1128,
      'scene' => 1,
      'im_type' => '其他本地服务',
    ];
    $header = [
      'Content-Type:application/json',
      'Access-Token:' . $resGetAccess['access_token']
    ];
    $res = $this->sendGETDouYin($url, $data, $header);
    return $res;
  }
  // 获取 access_token
  public function getAccessToken($array = array())
  {
    // DB::table('app_douyin_config')->where('shop_id', $array['shop_id'])->first();
    $url = 'https://developer.toutiao.com/api/apps/v2/token';
    $data = [
      'appid' => $array['app_id'],
      'secret' => $array['app_secret'],
      'grant_type' => 'client_credential',
    ];
    $header = [
      'Content-Type:application/json'
    ];
    $res = $this->sendDouYin($url, $data, $header);
    $this->log->info('抖音返回的access_token' . $res);
    $res = json_decode($res, true);
    if (isset($res['err_no']) && $res['err_no'] == 0) {
      $updateAccessToken = [
        'access_token' => $res['data']['access_token'],
        'time' => $res['data']['expiresAt'],
      ];
      DB::table('app_douyin_config')->where(['shop_id' => $array['shop_id']])->update(['parame' => $updateAccessToken]);
      return $updateAccessToken;
    }


    return [];
  }
  public function sendDouYin($url, $data, $headers)
  {
    // 测试使用
    // $return = '{"err_no":0,"err_tips":"success","data":{"session_key":"","openid":"","anonymous_openid":"VrBW4KrjY67LVJJ-","unionid":"","dopenid":""}}';
    // return $return;
    if (empty($url)) {
      $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
    }
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'POST',
      // CURLOPT_POSTFIELDS => json_encode($data, JSON_UNESCAPED_UNICODE),
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => $headers,
    ));

    $response = curl_exec($curl);
    if ($error = curl_error($curl)) {
      // var_dump($error);
      $this->log->info('返回的参数' . $error);
    }
    $this->log->info('参数:' . json_encode($data) . '提交url:' . $url . '返回结果:' . ($response));
    curl_close($curl);
    return $response;
  }
  public function sendGETDouYin($url, $data, $headers)
  {
    // 测试使用
    // $return = '{"err_no":0,"err_tips":"success","data":{"session_key":"","openid":"","anonymous_openid":"VrBW4KrjY67LVJJ-","unionid":"","dopenid":""}}';
    // return $return;
    if (empty($url)) {
      $url = 'https://developer.toutiao.com/api/apps/v2/jscode2session';
    }
    if (!empty($url)) {
      $url .= '?' . http_build_query($data);
    }
    // var_dump($url);
    $curl = curl_init();
    curl_setopt_array($curl, array(
      CURLOPT_URL => $url,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => '',
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => 'GET',
      CURLOPT_HTTPHEADER => $headers,
    ));

    $response = curl_exec($curl);
    if ($error = curl_error($curl)) {
      // var_dump($error);
      $this->log->info('返回的参数' . $error);
    }
    $this->log->info('参数:' . json_encode($data) . '提交url:' . $url . '返回结果:' . ($response));
    curl_close($curl);
    return $response;
  }
  public function getSign($map)
  {
    $rList = array();
    foreach ($map as $k => $v) {
      if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id") {
        continue;
      }

      $value = trim(strval($v));
      $len = strlen($value);
      if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"") {
        $value = substr($value, 1, $len - 1);
        $value = trim($value);
      }
      if ($value == "" || $value == "null") {
        continue;
      }
      array_push($rList, $value);
    }
    array_push($rList, "i9DE6aO73nz0BhGVYs153UaXbTPt82P7OLDV5kYb");
    sort($rList, 2);
    return md5(implode('&', $rList));
  }
}
